package com.stone.message.adapter.config;

import com.stone.message.adapter.infra.consumer.MessageConsumer;
import com.stone.message.adapter.infra.publisher.MessagePublisher;
import com.stone.message.adapter.infra.sender.MessageSender;
import com.stone.message.adapter.listener.ReceiveMessageEventListener;
import com.stone.message.adapter.listener.SendMessageEventListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.List;

/**
 * 消息适配自动注入配置类
 *
 * @author Mr_wenpan@163.com 2021/06/28 11:52
 */
@Configuration
public class StoneMessageAdapterAutoConfiguration {

    @Bean
    public MessagePublisher messagePublisher() {
        return new MessagePublisher();
    }

    /**
     * 注册消息事件监听器，监听容器中类型为ReceiveMessageEvent的消息。当容器中有类型为ReceiveMessageEvent的事件时
     * 该监听器就会通知对应的消费者进行消费
     *
     * @param messageConsumers 消息消费者集合
     */
    @Bean
    @ConditionalOnBean(MessageConsumer.class)
    public ReceiveMessageEventListener receiveMessageEventListener(List<MessageConsumer> messageConsumers) {
        ReceiveMessageEventListener receiveMessageEventListener = new ReceiveMessageEventListener();
        // 注册容器中的每一个消费者
        messageConsumers.forEach(receiveMessageEventListener::register);
        return receiveMessageEventListener;
    }

    @Bean
    @DependsOn("messageSender")
    @ConditionalOnMissingBean(SendMessageEventListener.class)
    public SendMessageEventListener sendMessageEventListener(List<MessageSender> messageSenders) {
        return new SendMessageEventListener(messageSenders);
    }

    /**
     * MessageSender是一个接口，接口不能直接注入，我们这里提供默认实现进行注入
     */
    @Bean
    public MessageSender messageSender() {
        return messageSender -> {
            // do nothing....
        };
    }
}
